package post_to_in_pkg.parser;
import java.util.Stack;

import post_to_in_pkg.node.OperandNode;


public class EnvStack {
	public EnvStack prev=null;
	public Stack<OperandNode> runtimeStack;
	
	public EnvStack(EnvStack env) {
		prev=env;
		/*
		 * in branch statement use another stack 
		 * to avoid the impact on the statement 
		 * out of the branch statement*/
		runtimeStack=new Stack<OperandNode>();
		
	}
	
	public boolean isLocalStackEmpty() {
		return runtimeStack.isEmpty();
	}

	public OperandNode pop() throws Exception {
		
		EnvStack pointer=this;
		while(pointer.runtimeStack.isEmpty()){
			pointer=pointer.prev;
			if(pointer==null)
				throw new Exception("stack is empty");
		}
		//here there will be an Exception occur
		return pointer.runtimeStack.pop();
	}
	
	public OperandNode peek() throws Exception{
		EnvStack pointer=this;
		while(pointer.runtimeStack.isEmpty()){
			pointer=pointer.prev;
			if(pointer==null)
				throw new Exception("stack is empty");
		}
		//here there will be an Exception occur
		return pointer.runtimeStack.peek();
	}
	
	public EnvStack clone() {
		EnvStack envstk=new EnvStack(null);
		envstk.runtimeStack=(Stack<OperandNode>)runtimeStack.clone();
		if(prev!=null) 
				envstk.prev=prev.clone();
		return envstk;
	}
	
	//define my own comparator 
	public boolean equals(EnvStack Env) {
		return Env.runtimeStack.isEmpty()&runtimeStack.equals(Env.prev.runtimeStack);
				
	}
	
	public boolean isEmpty() {
		EnvStack pointer=this;
		while(pointer.runtimeStack.isEmpty()) {
			if(pointer.prev!=null)
				pointer=pointer.prev;
			else
				break;
		}
		return pointer.runtimeStack.isEmpty();
	}
}
